<?php

session_start();

require_once ("conf/conf.php");
require_once ("locales/ro.php");
require ("include/function.php");

$action = isset ($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : "logout");

if ($action == 'login') {
    echo doLogin();
} else if ($action == 'logout') {
    session_unset();
    session_destroy();
    echo renderSuccess();
} else if ($action == 'resetpasswd') { // step 1 - sent mail
    echo doResetPasswordMail();
} else if ($action == 'reset') { // step 2 - click on reset password link
    doResetPassword();
} else if (isset($_SESSION['user_id'])) {
    if($action == 'changePassword'){ // step 3 - change password
        echo doChangePassword();
    }
} else {
    echo renderUnauthorized();
}


/**
 * @return string
 */
function doLogin(){
    $success = false;
    // TODO verify $email for SQL Injection
    $email = isset($_POST["email"]) ? trim($_POST["email"]) : "";
    $password = isset($_POST["password"]) ? $_POST["password"] : "";

    if ($email != "" && $password != "") {
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
        $password = md5($password);
        $sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password' AND status = 'active'";
        $r = do_query($sql);
        $total = mysql_fetch_array($r);
        if($total){
            $success = true;
            onLogin($total[0], $email);
        }
        db_disconnect($connection);
    }

    if($success){
        return renderSuccess();
    } else {
        return renderError(LOGIN_FAILED_MSG, LOGIN_FAILED_TITLE);
    }
}

/**
 * step 1
 * @return string
 */
function doResetPasswordMail(){
    $success = false;
    // TODO verify $email for SQL Injection
    $email = isset($_POST["email"]) ? trim($_POST["email"]) : "";
    $error = RESET_PASSWORD_ERROR_MSG;

    if ($email != "") { // TODO verify more
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);

        // verify if email exists
        $sql = "SELECT id FROM users WHERE email = '$email' AND status = 'active'";
        $r = do_query($sql);
        $total = mysql_fetch_array($r);
        // verify if email exists
        if($total){
            $key = getNewKey($email);

            $mail = sentResetPassMail($email, $key);

            if($mail['success']){

                $userId = $total[0];
                $sql="UPDATE users SET activationkey='$key' WHERE id = $userId";

                // insert in DB
                $r = do_query($sql);
                if($r){
                    $success = true;
                }
            } else {
                $error = $mail['message'];
            }
        } else {
            $error = RESET_PASSWORD_ERROR_MSG;
        }
        db_disconnect($connection);
    }

    if($success){
        return renderSuccess(str_replace("{0}", $email, RESET_PASSWORD_MSG), RESET_PASSWORD_TITLE);
    } else {
        return renderError($error, RESET_PASSWORD_TITLE);
    }
}


/**
 * @param  $emailTo
 * @param  $key
 * @return array (JSON Array)
 */
function sentResetPassMail($emailTo, $key){
    $siteName = $_SERVER['HTTP_HOST'];

    // TODO use reset-password-msg-ro.html
    //$body             = file_get_contents('include/register-msg-ro.html');
    //$body             = eregi_replace("[\]",'',$body);

    $url = "http://$siteName/auth.php?action=reset&key=$key";

    $body = "Dumneavoastră, sau altcineva a utilizat email-ul dvs. pentru a reseta parola pe $siteName.<br/>".
            "Puteţi completa schimbarea parolei accesând următorul link: <br/><br/>".
            "<a href=\"$url\" target=\"_blank\">$url</a><br/><br/>".
            "Dacă nu doriţi resetarea parolei, ignoraţi acest email.<br/>".
            "Binecuvantări, Echipa $siteName";

    $subject = "$siteName Resetare Parola";

    return sentMail($emailTo, $subject, $body);
}

/**
 * @return void
 */
function doResetPassword(){
    $key = $_GET["key"];
    if($key){
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
        $sql = "SELECT id, email FROM users WHERE activationkey = '$key' AND status = 'active'";
        $r = do_query($sql);
        $total = mysql_fetch_array($r);
        if($total){
            onLogin($total[0], $total[1]);
            $_SESSION['user_reset_pass_key'] = $key;
            resetActivationKey();
            header("Location: /#action=resetpass");
        }
        db_disconnect($connection);
    }
}

/**
 * @return string
 */
function doChangePassword(){
    $valid = false;
    $success = false;
    $error = '';
    $userId = $_SESSION['user_id'];

    if($userId){
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
        $sql = "SELECT password FROM users WHERE id = $userId AND status = 'active'";
        $r = do_query($sql);
        $total = mysql_fetch_array($r);

        if($total){
            $oldPassword = $_POST["oldPassword"];
            $key = $_SESSION['user_reset_pass_key'];

            $password = isset($_POST["password"]) ? $_POST["password"] : "";
            $password = md5($password);

            if(isset($oldPassword)){
                $oldPassword = md5($oldPassword);
                if($oldPassword == $total[0]){
                    $valid = true;
                } else {
                    $error = 'passWrong';
                }
            } else if(isset($key)){
                unset($_SESSION['user_reset_pass_key']);
                $valid = true;
            }

            if($valid){
                $key = getNewKey($_SESSION['user_email']);
                $sql="UPDATE users SET password='$password', activationkey = '$key' WHERE id = $userId";
                $r = do_query($sql);
                if($r){
                    $success = true;
                }
            }
        }
        db_disconnect($connection);
    }

    if($success){
        return renderSuccess();
    } else {
        return renderError($error);
    }
}

?>